<template>
  <div class="private-info admin-common-bg">
    <div class="left">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        label-width="110px"
        style="margin-top: 20px"
      >
        <el-form-item label="登陆账号" style="width: 80%">
          <el-input
            v-model="dataForm.adminUname"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" style="width: 80%" prop="nickname">
          <el-input
            v-model="dataForm.nickname"
            placeholder="请输入昵称"
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" style="width: 40%" prop="phone">
          <el-input
            v-model="dataForm.phone"
            placeholder="请输入手机号"
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" style="width: 28%" prop="gender">
          <el-select
            v-model="dataForm.gender"
            style="width: 100px"
            :clearable="true"
            autocomplete="off"
            @input="checkData"
          >
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上次登陆时间" style="width: 80%">
          <el-input
            v-model="dataForm.lastLoginTime"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间" style="width: 80%">
          <el-input
            v-model="dataForm.createTime"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="登陆ip" style="width: 80%">
          <el-input v-model="ip" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属地区" style="width: 80%">
          <el-input v-model="area" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item style="width: 80%">
          <el-tooltip
            :content="isChange ? '可修改' : '数据无变化，不可修改'"
            placement="top"
            effect="light"
          >
            <el-button
              type="success"
              :disabled="!isChange"
              @click="update"
              :loading="updateLoading"
              >完成</el-button
            >
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>
    <div class="right">
      <div class="avatar">
        <img :src="avatar || defaultAvatar" alt="" />
      </div>
      <div class="btn">
        <div class="updatePwd" @click="dialogVisible = true">
          <i class="el-icon-key"></i>修改密码
        </div>
        <div class="updateAvatar" @click="$refs.file.click()">
          <i class="el-icon-news"></i>
          <input type="file" @change="changeFile" hidden ref="file" />修改头像
        </div>
      </div>
    </div>
    <!-- 修改密码 -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @close="handleCloseUpdate"
    >
      <el-form
        ref="updatePwdForm"
        :model="updatePwdForm"
        :rules="updatePwdRules"
        label-width="90px"
      >
        <el-form-item label="旧密码" prop="oldPwd" style="width: 90%">
          <el-input
            v-model="updatePwdForm.oldPwd"
            placeholder="请输入旧密码"
            show-password
            :clearable="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd" style="width: 90%">
          <el-input
            v-model="updatePwdForm.newPwd"
            placeholder="请输入新密码"
            show-password
            :clearable="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="verifyPwd" style="width: 90%">
          <el-input
            v-model="updatePwdForm.verifyPwd"
            placeholder="请再次输入新密码"
            show-password
            :clearable="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item style="width: 80%">
          <el-button
            type="primary"
            @click="updatePwd"
            :loading="updatePwdLoading"
            >修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminInfo, updateAdminInfo } from "@/api/admin/admin";
import { uploadFile } from "@/api/common";
import defaultAvatar from "@/assets/defaultAvatar.png";
import userModule from "@/utils/userInfo";
import { Notification } from "element-ui";
export default {
  name: "PrivateInfo",
  data() {
    return {
      defaultAvatar,
      adminPwd: "",
      avatar: "",
      dataForm: {
        adminUname: "",
        nickname: "",
        phone: "",
        gender: "",
        lastLoginTime: "",
        createTime: "",
      },
      dataCopy: {},
      rules: {
        nickname: { required: true, message: "请输入昵称", trigger: "blur" },
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        gender: { required: true, message: "请选择性别", trigger: "change" },
      },
      updatePwdForm: {
        oldPwd: "",
        newPwd: "",
        verifyPwd: "",
      },
      updatePwdRules: {
        oldPwd: { required: true, message: "请输入旧密码", trigger: "blur" },
        newPwd: { required: true, message: "请输入新密码", trigger: "blur" },
        verifyPwd: {
          required: true,
          message: "请再次输入新密码",
          trigger: "blur",
        },
      },
      isChange: false,
      dialogVisible: false,
      updateLoading: false,
      updatePwdLoading: false,
      uploadLoading: false,
      // 新增ip地址和所属地区
      ip: "",
      area: "",
    };
  },
  created() {
    this.getAdminInfo();
  },
  methods: {
    // 获取管理员信息
    async getAdminInfo() {
      const userInfo = userModule.getUser();
      const res = await getAdminInfo(userInfo.id);
      const source = {
        id: res.data.id,
        adminUname: res.data.adminUname,
        nickname: res.data.nickname,
        phone: res.data.phone,
        gender: res.data.gender,
        lastLoginTime: res.data.lastLoginTime,
        createTime: res.data.createTime,
      };
      this.adminPwd = res.data.adminPwd;
      this.avatar = res.data.avatar;
      Object.assign(this.dataForm, source);
      Object.assign(this.dataCopy, source);
      this.dataForm.createTime = this.formatDate(this.dataForm.createTime);
      this.dataForm.lastLoginTime = this.formatDate(
        this.dataForm.lastLoginTime
      );
      this.dataForm.gender = this.dataForm.gender.toString();
      this.dataCopy.createTime = this.formatDate(this.dataCopy.createTime);
      this.dataCopy.lastLoginTime = this.formatDate(
        this.dataCopy.lastLoginTime
      );
      this.dataCopy.gender = this.dataCopy.gender.toString();
      // 新增IP地址和所属地区显示
      const user = userModule.getUser();
      this.ip = user.ip;
      const area = user.area;
      this.area = `${area.country}  ${area.province}省 ${area.city}市 ${
        area.district ? area.district + "区" : ""
      }`;
    },
    // 检查数据是否修改
    checkData() {
      for (let key in this.dataForm) {
        if (this.dataForm[key] !== this.dataCopy[key]) {
          this.isChange = true;
          return;
        }
      }
      this.isChange = false;
    },
    // 更新管理员信息
    async update() {
      this.$refs.dataForm.validate(async (v) => {
        if (v) {
          try {
            this.updateLoading = true;
            const res = await updateAdminInfo(this.dataForm);
            this.getAdminInfo();
            this.isChange = false;
          } finally {
            this.updateLoading = false;
          }
        }
      });
    },
    // 修改密码
    updatePwd() {
      this.$refs.updatePwdForm.validate(async (v) => {
        if (v) {
          if (this.adminPwd !== this.updatePwdForm.oldPwd) {
            this.$message.warning("旧密码错误");
            return;
          }
          if (this.updatePwdForm.newPwd !== this.updatePwdForm.verifyPwd) {
            this.$message.warning("两次输入的密码不一致");
            return;
          }
          try {
            this.updatePwdLoading = true;
            const res = await updateAdminInfo({
              id: this.dataForm.id,
              adminPwd: this.updatePwdForm.newPwd,
            });
            localStorage.setItem("a_t", "");
            localStorage.setItem("a_u", "");
            this.$router.push("/admin/login");
            this.$message.success("请重新登录");
          } finally {
            this.updatePwdLoading = false;
          }
        }
      });
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 选择文件，上传头像
    async changeFile(file) {
      // 判断格式是否正确
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }

      const notify = Notification({
        title: "提示",
        message: "上传中，请稍后...",
        iconClass: "el-icon-loading",
        duration: 0,
      });
      // 上传到服务器
      this.uploadLoading = true;
      try {
        let formData = new FormData();
        // 拿到存在file中的文件存放到formData中
        formData.append("file", file.target.files[0]);
        const res = await uploadFile(formData);
        this.avatar = res.data;
        const adminData = {
          id: this.dataForm.id,
          avatar: this.avatar,
        };
        await updateAdminInfo(adminData);
        this.getAdminInfo();
      } catch {
        notify.close();
        this.$notify.error({
          title: "错误",
          message: "上传失败，请重试",
          duration: 2000,
        });
      } finally {
        notify.close();
        this.$notify.success({
          title: "上传成功",
          duration: 2000,
        });
        this.uploadLoading = false;
      }
    },
    // 上传头像前校验格式
    verifyFormat(file) {
      const isJPG =
        file.target.files[0].type === "image/jpeg" ||
        file.target.files[0].type === "image/png";
      const isLt10M = file.target.files[0].size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
        return false;
      }
      return isJPG && isLt10M;
    },
    // 关闭对话框
    handleCloseUpdate() {
      this.$refs.updatePwdForm.resetFields();
      this.updatePwdLoading = false;
    },
  },
};
</script>

<style lang="less" scoped>
.private-info {
  display: flex;
  width: 100%;
  height: 600px;
  padding: 20px;
  .left {
    width: 60%;
    height: 100%;
    border-right: 2px solid #f1f1f1;
  }
  .right {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    width: 40%;
    height: 100%;
    .avatar {
      width: 220px;
      height: 220px;
      border-radius: 50%;
      img {
        width: 100%;
        height: 100%;
        border-radius: inherit;
      }
    }
    .btn {
      display: flex;
      flex-direction: column;
      height: 60px;
      justify-content: space-between;
      .updatePwd,
      .updateAvatar {
        padding: 4px 10px;
        margin-bottom: 16px;
        font-size: 13px;
        color: #888;
        cursor: pointer;
        border-radius: 4px;
        box-shadow: 1px 2px 5px #aaa;
        transition: all 0.4s;
        &:hover {
          transform: scale(1.1);
        }
        &:active {
          transform: scale(1);
        }
      }
    }
  }
}
</style>